#!/usr/bin/env python3
"""
数据库迁移脚本 - 添加用户设置字段
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from app.models.user import User

def migrate_add_user_settings():
    """添加用户设置字段"""
    app = create_app()
    
    with app.app_context():
        try:
            # 检查字段是否已存在
            inspector = db.inspect(db.engine)
            columns = [col['name'] for col in inspector.get_columns('users')]
            
            if 'settings' in columns:
                print("settings字段已存在，跳过迁移")
                return
            
            # 添加settings字段
            print("正在添加settings字段...")
            with db.engine.connect() as conn:
                conn.execute(db.text('ALTER TABLE users ADD COLUMN settings TEXT'))
                conn.commit()
            print("settings字段添加成功")
            
            # 为现有用户初始化默认设置
            print("正在为现有用户初始化默认设置...")
            users = User.query.all()
            default_settings = {
                'taskNotifications': True,
                'projectNotifications': True,
                'teamNotifications': True,
                'emailNotifications': True,
                'publicProfile': True,
                'showOnlineStatus': True,
                'theme': 'light',
                'language': 'zh-CN',
                'timezone': 'Asia/Shanghai',
                'dateFormat': 'YYYY-MM-DD',
                'timeFormat': '24h'
            }
            
            for user in users:
                if user.settings is None:
                    user.settings = default_settings
                    db.session.add(user)
            
            db.session.commit()
            print(f"已为 {len(users)} 个用户初始化默认设置")
            
        except Exception as e:
            print(f"迁移失败: {str(e)}")
            db.session.rollback()
            raise

if __name__ == '__main__':
    migrate_add_user_settings()
